package com.itcm.tcpdemo.components;

import com.itcm.tcpdemo.model.Packet;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

public class MyBusinessHandler extends SimpleChannelInboundHandler<Packet> {

    private static final Logger LOGGER = Logger.getLogger(MyBusinessHandler.class.getName());

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Packet packet) throws Exception {
        // 处理接收到的数据包
        LOGGER.log(Level.INFO, "Received packet: {0}", packet.toString());

        // 示例：根据消息类型执行不同的业务逻辑
        switch (packet.getMessageType()) {
            case 0x01: // Signal
                handleSignal(packet, ctx);
                break;
            case 0x02: // JSON Data
                handleJsonData(packet, ctx);
                break;
            default:
                throw new IllegalArgumentException("Unknown message type");
        }
    }

    private void handleSignal(Packet packet, ChannelHandlerContext ctx) throws Exception {
        // 简单回显信号
        ctx.writeAndFlush(packet);
    }

    private void handleJsonData(Packet packet, ChannelHandlerContext ctx) throws Exception {
        // 假设 JSON 数据已经通过 Jackson 解析为 Map
        Map<String, Object> jsonData = (Map<String, Object>) packet.getBody();

        // 检查事件类型并生成相应的响应
        if ("command".equals(jsonData.get("type"))) {
            List<Map<String, Object>> actions = (List<Map<String, Object>>) ((Map<String, Object>) jsonData.get("details")).get("actions");

            // 构建命令响应
            String jsonResponse = JsonResponseBuilder.buildCommandResponse(actions);
            sendResponse(ctx, jsonResponse);
        } else if ("chat".equals(jsonData.get("type"))) {
            // 构建聊天响应
            String[] answers = {"我叫抱抱喵呀。", "小明"};
            List<String> chatResponses = JsonResponseBuilder.buildChatResponses(answers, "huoshan", 1.4, "BV426_streaming", 1.1);

            for (String response : chatResponses) {
                sendResponse(ctx, response);
            }

            // 发送结束报文
            sendResponse(ctx, JsonResponseBuilder.buildEndResponse());
        } else {
            // 构建错误响应
            sendResponse(ctx, JsonResponseBuilder.buildErrorResponse("未知的消息类型", "failed"));
        }
    }

    private void sendResponse(ChannelHandlerContext ctx, String jsonResponse) throws Exception {
        // 创建一个新的 Packet 来封装 JSON 响应
        Packet responsePacket = new Packet((byte) 0x01, (byte) 0x02, (byte) 0x00, jsonResponse.getBytes(StandardCharsets.UTF_8).length);
        responsePacket.setBody(jsonResponse);

        // 发送响应给客户端
        ctx.writeAndFlush(Unpooled.wrappedBuffer(responsePacket.toBytes()));
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        LOGGER.log(Level.SEVERE, "Exception in MyBusinessHandler", cause);
        ctx.close();
    }
}